30. A couple of ways to inject in Angular
A couple of ways to inject in Angular
As you're probably coming to learn, there are several ways to do things in Angular. But, some ways have more pros than others. In the previous video, we injected a Service into a Controller using the array-style syntax. Notice that .controller()'s second argument is an array:
angular.module('udaciMealsApp')
.controller('MenuCtrl', ['foodFinder', function (menu) {
this.count = menu.count;
this.chef = menu.chef;
this.priceRange = menu.priceRange;
}]);
Another way to inject a Service is by passing a variable with a name that exactly matches the Service's name to directly inject the Service. With this approach, .controller()'s second argument is just the function:
angular.module('udaciMealsApp')
.controller('MenuCtrl', function (foodFinder) {
this.count = foodFinder.count;
this.chef = foodFinder.chef;
this.priceRange = foodFinder.priceRange;
});
There are a couple differences between these two, and the recommended approach is to use the array-style of injection. The array-style of injection let's you name the function's parameters anything you want. So if you don't like the name of the Service, you can still inject it but use a different variable name.
The array-style of injection is also required for minification. Minification takes all variables and makes them as small as possible. So it would convert every instance of foodFinder to just the letter a, for example. The direct injection approach reads the name of the parameter and injects the Service with that name. So when a Service named UserService is used, it might get minified to c, but Angular doesn't know of any Service with the name c. The minifier won't minify strings, so the array-style of injection is safe.
It can be very confusing reading information on the web that provides totally different ways to create Services. But now you know the different formats to create a Service and when one format might be better than another.